import { getLonLatArrayWall } from "@/api/CesiumUtils";
import {api} from "@/config/api";
import axios from "axios";
/**
 * @param {Viewer} viewer
 *
 */
export default class Dragentity {
    constructor(val){
        this.viewer = val.viewer;
        //移除所有实体
        //首先移除所有实体
        // this.postRender()
        this.cesium = val.cesium;
        this.viewer.entities.removeAll()
    }
    // 添加点
    addEntityforPoint(value){
        let that = this;
        let pinBuilder = new this.cesium.PinBuilder(); //添加标记https://cesium.com/learn/cesiumjs/ref-doc/PinBuilder.html?classFilter=PinBuilder
        // const url = Cesium.buildModuleUrl("Assets/Textures/maki/grocery.png");
        const url = `http://data.cubesatgarage.com:7777/prod-api${value.url}`
        let poin;
        // const url = "http://data.cubesatgarage.com:7777/prod-api/profile/upload/2022/03/19/%E6%B8%AF%E5%8F%A3_20220319092520A008.png"
        if(value.url){
            poin = Promise.resolve(
                pinBuilder.fromUrl(url,this.cesium.Color.YELLOW, 100)
            ).then(function (canvas) {
                return that.viewer.entities.add({
                    id:value.id,
                    name: value.name,
                    position: this.cesium.Cartesian3.fromDegrees(value.position.lon, value.position.lat,50),
                    billboard: {
                        image: canvas.toDataURL(),
                        verticalOrigin: this.cesium.VerticalOrigin.BOTTOM,
                    },
                });
            });
        }else {
            poin = this.viewer.entities.add({
                id:value.id,
                name: value.name,
                position: this.cesium.Cartesian3.fromDegrees(value.position.lon, value.position.lat,50),
                billboard: {
                    // image: pinBuilder.fromText(value.text,Cesium.Color.TURQUOISE, 100).toDataURL(),
                    image: pinBuilder.fromText(value.text,new this.cesium.Color(255,255,0,0.5), 100).toDataURL(),
                    verticalOrigin: this.cesium.VerticalOrigin.BOTTOM,
                },
                monitoItems:{
                    data:value
                },
            });
        }
        return poin
    }

    //添加光墙
    addEntityforWall(value){
        let alp = 1,
            num = 0;

        let pointsarr = [];
        value.points.forEach((points)=>{
            for(let j = 0 ; j < points.length; j++){
                for(var i = 0;i< points[j].length;i++){
                    let queryPoint = {};
                    queryPoint.x = points[0][i][0];
                    queryPoint.y = points[0][i][1];
                    pointsarr.push(queryPoint); //针对多个闭合的面
                }
            }
            // for(var i = 0;i< points[0].length;i++){
            //     let queryPoint = {};
            //     queryPoint.x = points[0][i][0];
            //     queryPoint.y = points[0][i][1];
            //     pointsarr.push(queryPoint); //针对多个闭合的面
            // }
        })
        console.log(pointsarr,this.cesium,this.cesium.Color)
        let self = this;
        var lonLatArrAall = getLonLatArrayWall(pointsarr,value.height);
        let wall = this.viewer.entities.add({
            id: value.bid,
            wall: {
                show: true,
                positions: new this.cesium.Cartesian3.fromDegreesArrayHeights(lonLatArrAall),
                // 扩散墙材质
                // material: new WallDiffuseMaterialProperty({
                //     color: new Cesium.Color(1.0, 1.0, 0.0, 1.0),
                //     // alpha:color.a * (fract(st.t)) * 0.8
                // }),
                material: new this.cesium.ImageMaterialProperty({
                    image: '/imgs/fade_yellow.png',
                    transparent: true,
                    color: new self.cesium.CallbackProperty(function () {
                        if (num % 2 === 0) {
                            alp -= 0.005
                        } else {
                            alp += 0.005
                        }
                        if (alp <= 0.3) {
                            num++
                        } else if (alp >= 1) {
                            num++
                        }
                        return self.cesium.Color.WHITE.withAlpha(alp)
                    }, false),
                }),
            },
        })
        return wall
    }


    //根据id移除实体
    removeEntity(val){
        val.viewer.entities.remove(this.viewer.entities.getById(val.id));
    }

    //输入直接进行判断
    showItemforWallandPoint(item){
        console.log(item.geometry.type);
        // let drag = this.dragEntity(); //初始化
        if(item.geometry.type == "MultiPolygon"){
            console.log("线")
            //Todo 添加光墙
            this.addEntityforWall({
                points:item.geometry.coordinates,
                height:25,
                bid:item.id
            })
            this.addEntityforPoint({
                id:item.id + "other",
                name:item.properties.NAME ? item.properties.NAME : "可用地",
                position:{
                    lon:item.properties.CLONGITUDE,
                    lat:item.properties.CLATITUDE
                },
                // text:item.properties.TYPE ? item.properties.TYPE : "可用地"
                text:item.properties.NAME ? item.properties.NAME : "可用地"
            })

            // addPoint(Cesium,this.viewer,item.properties.CLONGITUDE, item.properties.CLATITUDE,pointId)
        }else if(item.geometry.type == "Point"){
            console.log('点')
            //Todo 添加实体点

            // const url = this.cesium.buildModuleUrl("Assets/Textures/maki/grocery.png");
            // console.log(url)
            // const groceryPin = Promise.resolve(
            //     pinBuilder.fromUrl(url, Cesium.Color.GREEN, 48)
            // ).then(function (canvas) {
            //     return this.addEntityforPoint({
            //         name: "Grocery store",
            //         position: Cesium.Cartesian3.fromDegrees(-75.1705217, 39.921786),
            //         billboard: {
            //             image: canvas.toDataURL(),
            //             verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //         },
            //     });
            // });

            this.addEntityforPoint({
                id:item.id ,
                name:item.properties.NAME,
                position:{
                    lon:item.properties.CLONGITUDE ,
                    lat:item.properties.CLATITUDE
                },
                // text:item.properties.NAME
                text:item.properties.TYPE ? item.properties.TYPE : "可用地"
            })
        }
    }


    //场景渲染
    //添加场景事件
    addPostRender(lon,lat) {
        this.viewer.scene.postRender.addEventListener(this.postRender(), this);
    }


    //计算当前地图瓦片的级别
    // 获取当前地图瓦片级别
    tileLevel(){
        window.addEventListener("mousewheel",function (){
            let tiles = new Set();
            let tilesToRender = this.viewer.scene.globe._surface._tilesToRender;
            if (this.cesium.defined(tilesToRender)) {
                for (let i = 0; i < tilesToRender.length; i++) {
                    tiles.add(tilesToRender[i].level);
                }
                console.log("当前地图瓦片级别为:");
                console.log(tiles);
            }
        })
    }

    //场景渲染事件 实时更新窗口的位置 使其与笛卡尔坐标一致
    postRender() {
        // let position = Cesium.Cartesian3.fromDegrees(
        //     lon,
        //     lat,
        //     0
        // );
        let position = this.cesium.Cartesian3.fromDegrees(
            this.viewer.options._selectedEntity._position._value.x,
            this.viewer.options._selectedEntity._position._value.y,
            this.viewer.options._selectedEntity._position._value.z
        );
        if (!this.vmInstance.$el || !this.vmInstance.$el.style) return;
        const canvasHeight = this.viewer.scene.canvas.height;
        // const windowPosition = new Cesium.Cartesian2();
        const windowPosition = this.cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene,position);
        console.log(windowPosition);
        this.cesium.SceneTransforms.wgs84ToWindowCoordinates(
            this.viewer.scene,
            this.position,
            // windowPosition
        );
        this.vmInstance.$el.style.bottom =
            canvasHeight - windowPosition.y  +210+ "px";
        const elWidth = this.vmInstance.$el.offsetWidth;
        this.vmInstance.$el.style.left = windowPosition.x - elWidth / 2 +110 + "px";

        const camerPosition = this.viewer.camera.position;
        let height = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(camerPosition).height;
        height += this.viewer.scene.globe.ellipsoid.maximumRadius;
        if((!(this.cesium.Cartesian3.distance(camerPosition,this.position) > height))&&this.viewer.camera.positionCartographic.height<50000000){
            this.vmInstance.$el.style.display = "block";
        }else{
            this.vmInstance.$el.style.display = "none";
        }
    }
}
